//
//  NextViewController.m
//  4.线程保活
//
//  Created by 梁森 on 2020/1/17.
//  Copyright © 2020 梁森. All rights reserved.
//

#import "NextViewController.h"

#import "LSThread.h"

@interface NextViewController ()

@property (nonatomic, strong) LSThread * thread;
@property (assign, nonatomic, getter=isStoped) BOOL stopped;

@end

@implementation NextViewController

 - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor yellowColor];

     UIButton * redBtn = [UIButton buttonWithType:UIButtonTypeSystem];
     [self.view addSubview:redBtn];
     redBtn.frame = CGRectMake(100, 100, 50, 50);
     [redBtn setTitle:@"停止" forState:UIControlStateNormal];
     redBtn.backgroundColor = [UIColor redColor];
     [redBtn addTarget:self action:@selector(stop) forControlEvents:UIControlEventTouchUpInside];
     
     UIButton * redBtn1 = [UIButton buttonWithType:UIButtonTypeSystem];
     [self.view addSubview:redBtn1];
     redBtn1.frame = CGRectMake(200, 100, 50, 50);
     [redBtn1 setTitle:@"退出" forState:UIControlStateNormal];
     redBtn1.backgroundColor = [UIColor redColor];
     [redBtn1 addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
     
//    self.thread = [[LSThread alloc] initWithTarget:self selector:@selector(start) object:nil];
     
     __weak typeof(self) weakSelf = self;
     self.stopped = NO;
     self.thread = [[LSThread alloc] initWithBlock:^{
         NSLog(@"线程1开启做的第一件事...");
         NSLog(@"线程1开启做的第一件事...");
         NSLog(@"线程开始");
         [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
         while (weakSelf && !weakSelf.isStoped) {
             [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];   // 只开启一次RunLoop
         }
         NSLog(@"线程结束");
     }];
    [self.thread start];
}
- (void)dismiss{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)stop{
    if (!self.thread) return;
    [self performSelector:@selector(stopThread) onThread:self.thread withObject:nil waitUntilDone:YES];
}
- (void)stopThread{
    self.stopped = YES;
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.thread = nil;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (!self.thread) return;
    [self performSelector:@selector(doSth) onThread:self.thread withObject:nil waitUntilDone:NO];
}
- (void)doSth{
    NSLog(@"在线程1中继续做其他事...");
}

- (void)dealloc{
    NSLog(@"%s", __func__);
    [self stop];
}

@end
